package com.ccx.coachsite.ui.softmgr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ccx.coachsite.R;
import com.ccx.coachsite.api.CoachSiteApiAccessor;
import com.ccx.coachsite.api.CoachSiteSoftMgrApiAccessor;
import com.ccx.coachsite.downloadmgr.AsyncImageLoaderDetail;
import com.ccx.coachsite.downloadmgr.AsyncImageLoaderDetail.ImageCallback;
import com.ccx.coachsite.model.ServerResult;
import com.ccx.coachsite.model.SoftTopicItem;
import com.ccx.coachsite.ui.CommonAppView;

/**
 * 专题
 *
 */
public class SoftMgrTopicView extends CommonAppView {

	private Context mContext;
	private LayoutInflater mInflater = null;
	
	private boolean isLast = false;
	private int nextPage=1;
	private boolean mIsDownloading=false;//是否处在下载中
	
	/**服务端专题ID 过滤重复的专题*/
	private HashMap<String, String> topIDMap = new HashMap<String, String>();	
	
	public SoftMgrTabLazyView softMgrTabLazyView; //用来添加专题结果
	
	private ListView lv_required_list;			//显示列表
	private LinearLayout ll_on_loading_first; 	//第一次 正在加载...
	private LinearLayout ll_no_data_first;		//第一次 未找到数据或者网络错误
	private LinearLayout ll_on_loading_bottom;	//正在加载...
	private LinearLayout ll_no_data_bottom;		//未找到数据或者网络错误(底部)
	private TextView tv_nodata_error;			//未找到数据和出错的显示View
	private Button btn_nodata_reflash;			//未找到数据时刷新按钮
	
	//点击Item后把专题结果展示在此View
	private SoftMgrTopicWebView topicDetailListResultView = null; 
	
	private SoftTopicListViewAdapter softTopicListViewAdapter;
	
	/**专题列表更新消息 首次*/
	private static final int MESSAGE_TOPIC_LIST_UPDATE_FIRST = 1;
	
	/** 专题列表更新消息 非首次*/
	private static final int MESSAGE_TOPIC_LIST_UPDATE_OTHER = 2;
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MESSAGE_TOPIC_LIST_UPDATE_FIRST:
				Object[] objs = (Object[]) msg.obj;
				if (null == objs)
					return;
				
				ll_on_loading_first.setVisibility(View.GONE);
				
				ServerResult<SoftTopicItem> softTopicResult = (ServerResult<SoftTopicItem>)objs[0];
				ArrayList<SoftTopicItem> listSoftTopic = softTopicResult.itemList;
				
				if ( softTopicResult.isbNetworkProblem() ) {//网络连接失败提示
					tv_nodata_error.setText(R.string.common_no_connection);
					ll_no_data_first.setVisibility(View.VISIBLE);
				}else if ( listSoftTopic==null || listSoftTopic.size()==0 ){//未找到数据 
					tv_nodata_error.setText("");
					ll_no_data_first.setVisibility(View.VISIBLE);
				}else{
					softTopicListViewAdapter.addSoftTopicItems(listSoftTopic);
					softTopicListViewAdapter.notifyDataSetChanged();
					
					isLast = softTopicResult.getPageInfo().isLastPage();
					
					nextPage++;
				}
				mIsDownloading=false;
				break;
			case MESSAGE_TOPIC_LIST_UPDATE_OTHER:
				Object[] objsOther = (Object[]) msg.obj;
				if (null == objsOther)
					return;
				
				ll_on_loading_bottom.setVisibility(View.GONE);
				
				ServerResult<SoftTopicItem> softTopicResultOther = (ServerResult<SoftTopicItem>)objsOther[0];
				ArrayList<SoftTopicItem> listSoftTopicOther = softTopicResultOther.itemList;
				if ( softTopicResultOther.isbNetworkProblem() ) {//网络连接失败提示
					ll_no_data_bottom.setVisibility(View.VISIBLE);
				}else if ( listSoftTopicOther==null || listSoftTopicOther.size()==0 ){//未找到数据 
					
				}else{
					softTopicListViewAdapter.addSoftTopicItems(listSoftTopicOther);
					softTopicListViewAdapter.notifyDataSetChanged();
					
					isLast = softTopicResultOther.getPageInfo().isLastPage();
					
					nextPage++;
				}
				mIsDownloading=false;
			}
		}
	};
	
	public SoftMgrTopicView(Context paramContext) {
		super(paramContext);
		
		mContext = paramContext;
		mInflater = LayoutInflater.from( mContext );
	}

	/**
	 * 初始化界面
	 */
	public void initView() {
		addView(R.layout.soft_mgr_soft_topic_list);
		
		lv_required_list = (ListView) findViewById(R.id.lv_required_list);
		ll_on_loading_first = (LinearLayout) findViewById(R.id.ll_on_loading_first);
		ll_no_data_first = (LinearLayout) findViewById(R.id.ll_no_data_first);
		ll_on_loading_bottom=(LinearLayout)findViewById(R.id.ll_on_loading_bottom);
		ll_no_data_bottom = (LinearLayout) findViewById(R.id.ll_no_data_bottom);
		tv_nodata_error = (TextView) findViewById(R.id.tv_nodata_error);
		btn_nodata_reflash = (Button) findViewById(R.id.btn_nodata_reflash);

		lv_required_list.setOnItemClickListener(new ListItemClickListener());
		btn_nodata_reflash.setOnClickListener(new ReflashClickListener());
		
		softTopicListViewAdapter=new SoftTopicListViewAdapter(lv_required_list);
		lv_required_list.setAdapter(softTopicListViewAdapter);
	}
	
	/**
	 * 初始数据
	 */
	public void initData(){
		
		ll_no_data_first.setVisibility(View.GONE);
		ll_on_loading_first.setVisibility(View.VISIBLE);
		
		// 加载主题列表
		new Thread(new Runnable() {
			@Override
			public void run() {
				loadSoftTopic( );
			}
		}).start();
	}
	
	private void loadSoftTopic(){

		mIsDownloading=true;
		
		ServerResult<SoftTopicItem> softTopicResult = CoachSiteSoftMgrApiAccessor.getSoftMgrTopicList(nextPage);
		
		if (nextPage==1) { 
			Message msg = handler.obtainMessage(MESSAGE_TOPIC_LIST_UPDATE_FIRST, new Object[] { softTopicResult });
			msg.sendToTarget();
		}else{
			Message msg = handler.obtainMessage(MESSAGE_TOPIC_LIST_UPDATE_OTHER, new Object[] { softTopicResult });
			msg.sendToTarget();
		}
	}
	
	
    /**
     * 列表项点击，进入专题软件列表界面
     */
    private class ListItemClickListener implements OnItemClickListener{

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			
			ItemCache cache = (ItemCache) view.getTag();
			/*
			HashMap<String, Object> initParaMap = new HashMap<String, Object>();
			initParaMap.put(SoftMgrSoftListView.EXTRA_LIST_TYPE, SoftMgrSoftListView.TYPE_CATEGORY_LIST);
			initParaMap.put( "TopicName", cache.name.getText() );
			initParaMap.put( "TopicID", cache.id );
			initParaMap.put( "TopicURL", cache.details );
			
			topicDetailListResultView = new SoftMgrTopicWebView(mContext, initParaMap);
			softMgrTabLazyView.addResultView(topicDetailListResultView);
			*/
			
			Intent intent=new Intent(mContext,SoftMgrTopicWebDetail.class);
			intent.putExtra( "TopicName", cache.name.getText() );
			intent.putExtra( "TopicID", cache.id );
			intent.putExtra( "TopicURL", cache.details );
			mContext.startActivity(intent);
				
			/*
			// 分页测试
			if (!isLast) { 
				ll_no_data_bottom.setVisibility(View.GONE);
				ll_on_loading_bottom.setVisibility(View.VISIBLE);
				// 加载主题列表
				new Thread(new Runnable() {
					@Override
					public void run() {
						loadSoftTopic( );
					}
				}).start();
			}
			*/	
		}
    }//end ListItemClickListener
    
	public void addResultView(){
		
		if (topicDetailListResultView==null) return;
		this.addView(topicDetailListResultView);
	}
	
	/**
	 * 返回true表示移除了View、消化处理了back键
	 * @param resultsView
	 * @return
	 */
	public boolean removeResultView(){
		
		if ( topicDetailListResultView!=null && topicDetailListResultView.isShown() ){		
			topicDetailListResultView.clearCache();
			this.removeView(topicDetailListResultView);
			topicDetailListResultView = null;
			
			return true;
		}
		return false;
	}
	
	/**
	 * 1、返回back会调用次函数
	 * 2、再次点击选中的Tab时也会调用次函数,表示刷新View
	 */
	@Override
	public boolean flushView() {
		
		return removeResultView();
	}
	
	/******************************内部类区*********************************************/
	
    /**
     * 刷新数据的点击事件
     */
    private class ReflashClickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			initData();
		}
    	
    }// end ReflashClickListener
    
	private class SoftTopicListViewAdapter extends BaseAdapter {

		private int mVisibleLastIndex = 0;   //最后的可视项索引 
		
	    private ListView mListView;	    
	    private AsyncImageLoaderDetail mAsyncImageLoader;
	    
		private final List<SoftTopicItem> mList = new ArrayList<SoftTopicItem>();

		public SoftTopicListViewAdapter(ListView listView) {
			
			mListView = listView;
			mAsyncImageLoader = new AsyncImageLoaderDetail();
			
			mListView.setOnScrollListener(onScrollListener);
		}

		/**
		 * 增加主题
		 * 
		 * @param _listSoftTopic
		 */
		public void addSoftTopicItems(List<SoftTopicItem> _listSoftTopic) {
			
			List<SoftTopicItem> resultList = filterTopic(_listSoftTopic);
			mList.addAll(resultList);
		}

		/**
		 * 清空数据
		 */
		public void clear() {
			mList.clear();
		}

		@Override
		public int getCount() {
			
			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			View view = convertView;
			
			ItemCache cache = null;
			if (null == view) {
				view = mInflater.inflate(R.layout.soft_mgr_soft_topic_list_item, null);
				cache = new ItemCache(view);
				view.setTag(cache);
			} else {
				cache = (ItemCache) view.getTag();
			}
			
			SoftTopicItem tmpView = mList.get(position);
			cache.id = tmpView.getId();
			cache.details = tmpView.getDetails();
			cache.name.setText( tmpView.getName() );
			cache.desc.setText( tmpView.getDesc() );
			
			String imgUrl = tmpView.getTypeUrl();
			
			if (!imgUrl.startsWith("http"))
				imgUrl = CoachSiteApiAccessor.BASE_URL + imgUrl;
			
			cache.typeUrl.setTag(imgUrl);					
			Drawable cachedImage = mAsyncImageLoader.loadDrawable(imgUrl, new ImageCallback() {
	            public void imageLoaded(Drawable imageDrawable, String imageUrl) {
	            	if ( mListView ==null )return; 
	                ImageView imageViewByTag = (ImageView) mListView.findViewWithTag(imageUrl);
	                if (imageViewByTag != null && imageDrawable!=null) {		                	
	                    imageViewByTag.setImageDrawable(imageDrawable);
	                }
	            }
	        });
			if (cachedImage == null) {
				cache.typeUrl.setImageResource(R.drawable.soft_loading_default);
			}else{
				cache.typeUrl.setImageDrawable(cachedImage);
			}
			
			return view;
			
		}
		
		AbsListView.OnScrollListener onScrollListener = new AbsListView.OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				
				int itemsLastIndex = getCount()-1;
				if ( view.getLastVisiblePosition() == itemsLastIndex &&!isLast &&!mIsDownloading ) {
					ll_no_data_bottom.setVisibility(View.GONE);
					ll_on_loading_bottom.setVisibility(View.VISIBLE);
					
					// 加载主题列表
					new Thread(new Runnable() {
						@Override
						public void run() {
							loadSoftTopic( );
						}
					}).start();
				}				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		};
		
		
		/**
		 * 过滤掉重复的专题
		 * @param _listTopicItem
		 */
		private List<SoftTopicItem> filterTopic(List<SoftTopicItem> _listTopicItem){
			
			List<SoftTopicItem> resultList = new ArrayList<SoftTopicItem>();
			
			String topID = "";
			SoftTopicItem topicItem = null; 
			
			for (int i = 0; i < _listTopicItem.size(); i++) {
				topicItem = _listTopicItem.get(i);
				topID = topicItem.getId();
				
				if ( topIDMap.get(topID)==null ){
					topIDMap.put(topID,topID);
					resultList.add(topicItem);
				}
			}
			
			return resultList;
		}
	}

	class ItemCache {
		public String id;
		public String details;
		public TextView name;
		public TextView desc;
		public ImageView typeUrl;
		public TextView appCount;
		

		public ItemCache(View view) {
			name = (TextView) view.findViewById(R.id.name);
			desc = (TextView) view.findViewById(R.id.desc);
			typeUrl = (ImageView) view.findViewById(R.id.typeUrl);
		}
	}
    
}
